package cn.rkylin.oms.push.controller;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.ectrade.service.IEcTradeService;
import cn.rkylin.oms.ectrade.vo.EcTradeVO;
import cn.rkylin.oms.push.adapter.PushAdapter;
import cn.rkylin.oms.push.adapter.PushAdapterFactory;
import cn.rkylin.oms.push.request.PushSystemConsignment;
import cn.rkylin.oms.push.request.PushTradeMemo;
import cn.rkylin.oms.push.request.PushTradeOfflineSend;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.Serializable;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/pushTrade")
public class PushTradeController extends ApolloController {
    private static final Log logger = LogFactory.getLog(PushTradeController.class);
    @Resource(name = "redisTemplate")
    private RedisTemplate<Serializable, Serializable> redisTemplate;
    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;
    @Autowired
    private IEcTradeService ecTradeService;
    @Autowired
    private LogUtil logUtil;

    /**
     * 系统发货接口
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushSystemConsignment", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushSystemConsignment(@RequestBody PushSystemConsignment request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcTradeCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushSystemConsignment(shop, request.getEcItemCode(), request.getEcTradeCode(),
                    request.getEcSkuCode(), request.getShipTime());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 自己联系物流（线下物流）发货接口
     *
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    @ResponseBody
    @RequestMapping(value = "/pushConsign", method = RequestMethod.GET)
    public Map<String, Object> pushConsign(String pushTradeOfflineSend) throws Exception {
        String pushTradeOfflineSendStr = URLDecoder.decode(pushTradeOfflineSend);
        PushTradeOfflineSend pushTradeOfflineSendData = JSON.parseObject(pushTradeOfflineSendStr,
                PushTradeOfflineSend.class);

        return this.pushTradeOfflineSend(pushTradeOfflineSendData);
    }

    /**
     * 自己联系物流（线下物流）发货接口 - 平台发货接口
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushTradeOfflineSend", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushTradeOfflineSend(@RequestBody PushTradeOfflineSend request) {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcTradeCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushTradeOfflineSend(shop, request.getEcTradeCode(), request.getLgstNo(),
                    request.getLgstCode());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
            logUtil.error(new DBLog(request.getEcTradeCode(), "oms_exception", "pushTradeOfflineSend",
                    "接口  平台发货接口异常: " + ex.getMessage()), ex);
        }
        return resultMap;
    }

    /**
     * 修改一笔交易备注
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushTradeMemo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushTradeMemo(@RequestBody PushTradeMemo request) {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), String.valueOf(request.getTid()));
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushTradeMemo(shop, request.getTid(), request.getMemo(), request.getFlag());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
            logUtil.error(new DBLog(String.valueOf(request.getTid()), "oms_exception", "pushTradeMemo",
                    "接口  修改平台备注接口异常: " + ex.getMessage()), ex);
        }
        return resultMap;
    }

    /**
     * 请求参数验证
     *
     * @throws Exception
     */
    private Map<String, Object> pushDataValidate(String shopId, String ecTradeCode) throws Exception {

        Map<String, Object> resultMap = new HashMap<>();

        // shopId 没有的场合
        if (StringUtils.isEmpty(shopId)) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺不存在");
            return resultMap;
        }
        // ecItemCode 没有的场合
        if (StringUtils.isEmpty(ecTradeCode)) {
            resultMap.put("success", "n");
            resultMap.put("msg", "交易数据不存在");
            return resultMap;
        }

        // // 根据ecItemCode取得ecitem的主键
        // List<String> listEcItem = getEcTrade(shopId, ecTradeCode);
        // if (listEcItem == null || listEcItem.size() <= 0) {
        // resultMap.put("success", "n");
        // resultMap.put("msg", "交易数据不存在");
        // return resultMap;
        // }

        Shop shop = getShop(shopId);
        if (shop == null || StringUtils.isEmpty(shop.getEnable()) || StringUtils.isEmpty(shop.getDeleted())) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺不存在");
            return resultMap;
        } else if (shop.getEnable().equalsIgnoreCase("n")) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺未启用");
            return resultMap;
        } else if (shop.getDeleted().equalsIgnoreCase("y")) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺已删除");
            return resultMap;
        }

        // 如果是子店铺
        if (StringUtils.isNotEmpty(shop.getParentShop())) {
            Shop shopParent = getShop(shop.getParentShop());
            shop.setApiUrl(shopParent.getApiUrl());
            shop.setAppKey(shopParent.getAppKey());
            shop.setAppSecret(shopParent.getAppSecret());
            shop.setSessionKey(shopParent.getSessionKey());
        }

        resultMap.put("shop", shop);
        PushAdapter pushAdapter = PushAdapterFactory.getPushAdapter(shop);
        if (pushAdapter == null) {
            resultMap.put("success", "n");
            resultMap.put("msg", "pushAdapter is null");
            return resultMap;
        }
        resultMap.put("pushAdapter", pushAdapter);
        return resultMap;
    }

    /**
     * 取得原始单据的shopID
     *
     * @param listEctradeId
     * @return
     */
    private String getShopIdByTrade(List<String> listEctradeId) {
        String shopId = "";
        try {
            for (int i = 0; i < listEctradeId.size(); i++) {
                EcTradeVO ecTradeVO = ecTradeService.getEcTradeById(listEctradeId.get(i));
                if (ecTradeVO.getEcTradeId().equals(ecTradeVO.getParentTradeId())) {
                    shopId = ecTradeVO.getShopId();
                    break;
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return shopId;
    }

    /**
     * 根据shopId取得shop对象
     *
     * @param shopid
     * @return
     */

    private ShopVO getShop(String shopid) {
        ShopVO shopVO = null;
        try {
            shopVO = StringUtils.isNotBlank(shopid) ? shopService.getShopById(shopid) : null;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            shopVO = null;
        }
        return shopVO;
    }

    /**
     * 根据tid取得Ectrade对象
     *
     * @param tid
     * @return
     */

    private List<String> getEcTrade(String shopId, String tid) {
        List<String> listEctrade = new ArrayList<String>();
        try {
            EcTradeVO parameter = new EcTradeVO();
            EcTradeVO ecTradeVO = null;
            parameter.setShopId(shopId);
            parameter.setEcTradeCode(tid);
            List<EcTradeVO> list = ecTradeService.findByTid(parameter);
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    ecTradeVO = list.get(i);
                    listEctrade.add(ecTradeVO.getEcTradeId());
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            listEctrade = null;
        }
        return listEctrade;
    }

}
